<?php
namespace control;

/*
*角色类
*/

class roleClass extends adIndexClass
{
    /*列表页-查询条件*/
    public function home()
    {
        $html =
            text(array("name" => "name", "title" => '{l.role.home.name}')) .
            select(array("name" => "powerOne", "title" => "{l.role.home.powerOne}", "option" => array_keys($this->powerAll), "change" => "getPowerTwo")) .
            select(array("name" => "powerTwo", "title" => "{l.role.home.powerTwo}", "change" => "getPowerThree")) .
            select(array("name" => "powerThree", "title" => "{l.role.home.powerThree}"));
        //返回
        return $this->homeFun($this->search($html));
    }

    /*列表页-查询结果*/
    public function homeSearch()
    {
        $powerSearch = $or = '';
        //like查询数组
        $like = [
            "name" => $this->post('name'),//角色名称
        ];
        //权限查询
        $powerOne = $this->post('powerOne');    //一级导航
        $powerTwo = $this->post('powerTwo');    //二级导航
        $powerThree = $this->post('powerThree');  //三级导航
        if ($powerOne) {
            // 二级不存在
            if (!$powerTwo) {
                $and = "";
                foreach ($this->powerAll[$powerOne] as $twoArray) {
                    foreach ($twoArray as $key => $value) {
                        if ($and) {
                            $or = " or ";
                        }
                        $and .= $or . " power like '%\"$key\":%' ";
                    }
                }
                $powerSearch = " and ( " . $and . " ) ";
            } elseif (!$powerThree) {
                // 二级存在，判断三级是否存在
                (array)$data = array_keys($this->powerAll[$powerOne][$powerTwo]);
                $and = "";
                foreach ($data as $value) {
                    if ($and) {
                        $or = " or ";
                    }
                    $and .= $or . " power like '%\"$value\":%' ";
                }
                $powerSearch = " and ( " . $and . " ) ";
            } else {
                $powerSearch = " and power like '%\"$powerThree\":%' ";
            }
        }
        //获取查询结果
        $where = search(["like" => $like]) . $powerSearch;
        $page = $this->page(array("table" => "role", "where" => $where, "order" => "list"));
        //获取表头
        $checkAll = $this->checkAll("listForm", "roleId");
        $tr[] = array($checkAll, L('setting.table.jsmc'), L('setting.table.zuozhe_xian'), L('setting.table.pai_xu_hao') . orderByAscStyle);
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = $this->dominate(array(
                "box" => array("name" => "roleId", "value" => $array['id']),
                "detail" => array("title" => L('setting.table.jsxq'), "click" => "newIframe('" . L('setting.table.jsxq') . "','" . root . "control/adIndex.html?cla=role&fun=detail&id=" . $array['id'] . "')"),
            ));
            //权限
            $power = "";
            $powerNow = json_decode($array['power'], true);
            if (!$powerOne) {
                foreach ($this->powerAll as $oneKey => $twoArray) {
                    foreach ($twoArray as $menuOneName => $menuOneValue) {
                        if (count(array_intersect_key($menuOneValue, (array)$powerNow)) > 0) {
                            $power .= $menuOneName . "；";
                        }
                    }
                }
            } elseif (!$powerTwo) {
                foreach ($this->powerAll[$powerOne] as $oneKey => $twoArray) {
                    foreach ($twoArray as $menuTwoName => $menuTwoValue) {
                        if (isset($powerNow[$menuTwoName]) && count(array_intersect(array_keys($menuTwoValue), (array)$powerNow[$menuTwoName])) > 0) {
                            $power .= $menuTwoValue['name'] . "；";
                        }
                    }
                }
            } else {
                foreach ($this->powerAll[$powerOne][$powerTwo] as $menuTwoName => $menuTwoValue) {
                    if (isset($powerNow[$menuTwoName]) && count(array_intersect(array_keys($menuTwoValue), (array)$powerNow[$menuTwoName])) > 0) {
                        $power .= $menuTwoValue['name'] . "；";
                    }
                }

            }
            //本列
            $tr[] = array($dominate, $array['name'], '<span class="power-text">' . $power . '</span>', $array['list']);
        }
        //控件
        $button = "";
        if ($this->power("role", "edit")) {
            $button .= "
			<span class='spanButton' onclick=\"layer('role','edit',{id:'" . suiji() . "'})\">".L('setting.table.new_role')."</span>
			<span onclick=\"pasWarn('listForm','role','delete')\" class='spanButton'>".L('setting.table.delAll')."</span>
			";
        }
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . space . $this->tableMany(array("tr" => $tr)) . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /*编辑角色档案-弹出层*/
    public function edit()
    {
        $id = $this->post('id') ? $this->post('id') : '';
        //数据查询
        $role = query("role", " id = '" . $id . "' ");
        //表单
        $html = $this->layerEdit(array(
            "table" => array(
                array(
                    must . L('setting.table.jsmc') . "：" => text(["name" => "name", "value" => $role['name'],]),
                    must . L('setting.table.pai_xu_hao') . "：" => text(["name" => "list", "value" => $role['list'],]),
                ),
                array(
                    must . L('setting.table.bei_zhu') . "：" => textarea(["name" => "text", "value" => $role['text']]),
                ),
            ),
        ));
        //返回
        return $this->layer(["title" => L('setting.table.bian_ji_jiao_se'), "height" => 270, "html" => $html]);
    }

    /*角色详情页~基本信息-异步处理*/
    public function editEdit()
    {
        //赋值
        $field = array(
            "name" => $this->post('name'),//角色名称
            "list" => $this->post('list'),//排序号
            "text" => $this->post('text'),//职位描述
            "updateTime" => date("Y-m-d H:i:s"),//更新时间
        );
        $role = query("role", " id = '" . $this->post('id') . "' ");
        //判断
        if (!$this->power("role", "edit")) {
            $json['warn'] = L('setting.table.nmzbjjsdzx');
        } elseif (empty($field['name'])) {
            $json['warn'] = L('setting.table.qtxjsmc');
        } elseif (sqlNum("role", " name = '$field[name]' and id != '" . $this->post('id') . "' ") > 0) {
            $json['warn'] = L('setting.table.gjsyjcz');
        } elseif (empty($field['list'])) {
            $json['warn'] = L('setting.table.qtxpxh');
        } elseif (preg_match(checkInteger, $field['list']) == 0) {
            $json['warn'] = L('setting.table.pxhbxwzzs');
        } elseif (empty($field['text'])) {
            $json['warn'] = L('setting.table.qjymsgjs');
        } elseif (empty($this->post('id'))) {
            $json['warn'] = L('setting.table.roleIdEmpty');
        } elseif (empty($role['id'])) {
            $field = array_merge($field, array("id" => $this->post('id'), "time" => date("Y-m-d H:i:s")));
            $json['warn'] = static::insert(["table" => "role", "field" => $field]);
        } else {
            $json['warn'] = static::update(["table" => "role", "field" => $field, "where" => "id = '" . $this->post('id') . "'"]);
        }
        if (in_array($json['warn'], ["新增成功", "更新成功"])) {
            //添加日志
            $type = mb_substr($json['warn'], 0, 2, 'utf-8');
            $text = str_replace(['{{staffName}}', '{{name}}'], [$this->control['name'], $field['name']], L('setting.table.role_edit_text'));
            $this->logText(["type" => "role", "text" => $text]);
            //提示
            $_SESSION['warn'] = $json['warn'];
            $json['warn'] = 2;
        }
        //返回
        return json_encode($json, 320);
    }

    /*行政人事-角色管理-角色详情页*/
    public function detail()
    {
        $role = query("role", " id = '" . $this->get('id') . "' ");
        if (!$this->power("role", "see")) {
            $html = L('setting.table.nmzjsckzx');
        } elseif (empty($this->get('id'))) {
            $html = L('setting.table.roleIdEmpty');
        } elseif (empty($role['id'])) {
            $html = L('setting.table.wzdcjs');
        } else {
            $data = [
                "id" => $role['id'],
                "title" => $role['name'],
                "menu" => [
                    "detail" => L('setting.table.ji_ben_xin_xi'),
                    "tabPower" => L('setting.table.zxsz'),
                ],
            ];
            //按钮
            $button = [];
            if ($this->power("role", "edit")) {
                $button[] = array(
                    "name" => L('setting.table.edit'),
                    "type" => "弹出层",
                    "cla" => "role",
                    "fun" => "edit",
                    "post" => array("id" => $role['id']),
                    'style' => 'li-btn-blue-bg',
                );
                $button[] = array(
                    "name" => L('setting.table.fu_zhi'),
                    "type" => "弹出层",
                    "cla" => "role",
                    "fun" => "copy",
                    "post" => array("id" => $role['id']),
                );
            }
            //生成表单
            $data['html'] = $this->tableShow(array(
                "button" => $button,
                L('setting.table.jiao_se_dang_an') => array(
                    array(
                        L('setting.table.jsmc') => $role['name'],
                        L('setting.table.pai_xu_hao') => $role['list'],
                        L('setting.table.roleId') => $role['id'],
                    ),
                    array(
                        L('setting.table.gxsj') => $role['updateTime'],
                        L('setting.table.cjsj') => $role['time'],
                    ),
                    array(
                        L('setting.table.bei_zhu') => "<pre>" . kong($role['text']) . "</pre>",
                    ),
                ),
            ));
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    /*行政人事-角色管理-详情页-权限设置-页面*/
    public function tabPower()
    {
        //数据库查询
        $role = query("role", " id = '" . $this->get('id') . "' ");
        if (!$this->power("role", "see")) {
            $json['warn'] = L('setting.table.nmzjsckzx');
        } elseif (empty($this->get('id'))) {
            $json['warn'] = L('setting.table.roleIdEmpty');
        } elseif (empty($role['id'])) {
            $json['warn'] = L('setting.table.wzdcjs');
        } else {
            //遍历权限
            $power = json_decode($role['power'], true);
            $html = "";

            foreach ($this->powerAll as $title => $all) {
                $html .= "<div class='main'><h2>$title</h2>";
                $line = '';
                foreach ($all as $type => $module) {
                    unset($module['attribute']);//过滤掉属性
                    $box = "";
                    $checkAll = "checked";
                    foreach ($module as $key => $value) {
                        $name = $value['name'];
                        unset($value['name']);
                        unset($value['cla']);
                        unset($value['fun']);
                        $checkedTemp = $power[$key] ?? '';
                        $box .= "<p>" . checkbox(array("name" => "power[" . $key . "]", 'other' => "data-power='$key'", "value" => $value, "checked" => $checkedTemp, "title" => $name)) . "</p>";
                        if (array_keys($value) != $checkedTemp) {
                            $checkAll = "";
                        }
                    }
                    $html .= "
				<div class='box " . $line . "'>
					<p><label class='checkbox'><input type='checkbox' onchange=\"powerCheckAll(this)\" " . $checkAll . "><span></span>\n" . $type . "</label></p>
					" . $box . "
				</div>";
                    $line = "line";//分隔线
                }
                $html .= '</div>';
            }
            //隐藏域
            $hidden = hidden(array("name" => "id", "value" => $role['id']));
            //控件
            $button = "";
            if ($this->power("role", "power")) {
                $select = L('setting.table.select');
                $cancelSelect = L('setting.table.cancelSelect');
                $update = L('setting.table.update');
                $button .= <<<EOT
                <ul class="liButton">
	                <li onclick="$('[type=\'checkbox\']').prop('checked', true)" class="li-btn-alert">$select</li>
	                <li onclick="$('[type=\'checkbox\']').prop('checked', false)" class="li-btn-alert">$cancelSelect</li>
                    <li onclick="commitPower('powerForm', root+'control/adIndex.html?cla=role&fun=powerEdit')" class="li-btn-alert li-btn-blue-bg">$update</li>
                </ul>
EOT;
            }
            //生成表单
            $json['html'] = $button . "<form name='powerForm'>" . $html . $hidden . "</form>" . $this->js();
        }
        //返回
        return json_encode($json, 320);
    }

    /**
     * JS
     */
    private function js(): string
    {
        return <<<eof
<script>
function commitPower(form,url){
      let con = setTimeout(function (){
        $("#loading", parent.document).hide();
    },15000);
    // $("#loading", parent.document).show();
        let power = {};
        $("[name=" +form + "] input[data-power]:checked").each(function() {
            let name = $(this).data('power');
             if (power[name]) {
                   power[name].push($(this).val());
             }else{
                  power[name] = [$(this).val()];
             }
        })
        let id = $("[name=" +form + "] input[name='id']").val();
        //异步提交数据
        $.post(url,{jsonData:JSON.stringify(power),id:id}, function (data) {
            if (data.warn === 2 || data.warn === '2') {
                if (data.href) { //如果异步返回的json参数中定义了重定向url，则跳转到本url
                    window.location.href = data.href;
                } else {
                    window.location.reload();
                }
            } else {
                warn(data.warn, 'error');
            }
            $("#loading", parent.document).hide();
            clearTimeout(con);
        }, "json");
}
$.fn.serializeJson = function() {
        var serializeObj = {};
        var array = this.serializeArray();
        $(array).each(function() {
            if (serializeObj[this.name]) {
                if ($.isArray(serializeObj[this.name])) {
                    serializeObj[this.name].push(this.value);
                } else {
                    serializeObj[this.name] = [serializeObj[this.name], this.value];
                }
            } else {
                serializeObj[this.name] = this.value;
            }
        });
        return serializeObj;
    };
</script>
eof;
    }

    /**
     * 复制
     */
    public function copy()
    {
        $info = query("role", " id = '" . $this->post('id') . "' ");
        if (!$this->power("role", "power")) {
            $json['warn'] = L('setting.table.nmzbjjsdzx');
        } elseif (empty($this->post('id'))) {
            $json['warn'] = L('setting.table.roleIdEmpty');
        } elseif (empty($info['id'])) {
            $json['warn'] = L('setting.table.wzdcjs');
        } else {
            $field = [
                'id' => self::getId(),
                'name' => $info['name'] . ' - ' . L('setting.table.copy'),
                'list' => $info['list'] + 1,
                'text' => $info['text'],
                'power' => $info['power'],
                'updateTime' => $this->time,
                'time' => $this->time,
            ];
            $json['warn'] = static::insert([
                'table' => 'role',
                'field' => $field,
            ]);
            if (in_array($json['warn'], array("新增成功", "更新成功"))) {
                //添加日志
                $text = str_replace(['{{staffName}}', '{{name}}'], [$this->control['name'], $info['name']], L('setting.table.copy_text'));
                $this->logText(array("type" => "role", "text" => $text));
                //提示
                $_SESSION['warn'] = L('setting.table.fzzxcg');
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=role&fun=detail&id=" . $field['id'];
            }
            //添加日志
        }
        //返回
        return json_encode($json, 320);
    }


    /**
     * 获取两个字符中间的字符串
     *
     * @param $input
     * @param $start
     * @param $end
     * @return string
     */
    private function cutBetween($input, $start, $end): string
    {
        return substr($input, strlen($start) + strpos($input, $start), (strlen($input) - strpos($input, $end)) * (-1));
    }

    /*行政人事-角色管理-详情页-权限设置-异步处理*/
    public function powerEdit()
    {
        $result['power'] = json_decode($_POST['jsonData'], true);
        $result['id'] = $this->post('id');
        $role = query("role", " id = '" . $result['id'] . "' ");
        //判断
        if (!$this->power("role", "power")) {
            $json['warn'] = L('setting.table.nmzbjjsdzx');
        } elseif (empty($result['id'])) {
            $json['warn'] = L('setting.table.roleIdEmpty');
        } elseif (empty($role['id'])) {
            $json['warn'] = L('setting.table.wzdcjs');
        } elseif (!isset($result['power']) || !is_array($result['power']) || empty($result['power'])) {
            $json['warn'] = L('setting.table.qgxxydzx');
        } else {
            $json['warn'] = update(array(
                "table" => "role",
                "field" => array(
                    "power" => json_encode($result['power']),
                    "updateTime" => date("Y-m-d H:i:s"),
                ),
                "where" => " id = '$role[id]' ",
            ));
            if (in_array($json['warn'], array("新增成功", "更新成功"))) {
                //添加日志
                $text = str_replace(['{{staffName}}', '{{name}}'], [$this->control['name'], $role['name']], L('setting.table.edit_text'));
                $this->logText(array("type" => "role", "text" => $text));
                //提示
                $_SESSION['warn'] = L('setting.table.zxszcg');
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=role&fun=detail&menu=tabPower&id=" . $role['id'];
            }
            //添加日志
        }
        //返回
        return json_encode($json, 320);
    }

    /*行政人事-角色管理-删除角色*/
    public function delete()
    {
        if (!$this->power("role", "edit")) {
            $json['warn'] = L('setting.table.zxbz');
        } elseif (empty($this->post('roleId'))) {
            $json['warn'] = L('setting.table.nygjsdmzxzn');
        } elseif (empty($this->post('password'))) {
            $json['warn'] = L('setting.table.qsrdlmm');
        } elseif (verifyPwd($this->post('password'), self::$user['password']) === false) {
            $json['warn'] = L('setting.table.dlmmsrcw');
        } else {
            $x = 0;
            $txt = "";
            foreach ($this->post('roleId') as $id) {
                //数据准备
                $role = query("role", " id = '$id'");
                if (sqlNum("user", " role like '%$id%' ") > 0) {
                    $txt .= str_replace(['{{name}}'], [$role['name']], L('setting.table.role_del_warn_one'));
                } elseif ($role['isDel']) {
                    $txt .= str_replace(['{{name}}'], [$role['name']], L('setting.table.role_del_warn_two'));
                } else {
                    //最后删除角色基本参数
                    delete(["table" => "role", "where" => " id = '$id' "]);
                    //返回
                    $txt .= $role['name'] . L('setting.table.sccg');
                    $x++;
                }
            }
            //添加记录
            $logText = str_replace(['{{staffName}}', '{{x}}'], [$this->control['name'], $x], L('setting.table.role_del_text')) . $txt;
            $this->logText(array("type" => "role", "text" => $logText));
            //返回
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('setting.table.role_del_msg'));
            $json['warn'] = 2;
        }
        //返回JSON
        return json_encode($json, 320);
    }

    /*行政人事-角色管理-根据一级导航返回二级导航*/
    public function getPowerName()
    {
        $field = $this->post('field') ?: 'name';
        $value = $this->post('value') ?: '';
        $name = $this->post('name');
        $level = $this->post('level');
        if ($level == 3) {
            $json['res'] = getPowerThree($name, $value, $field);
        } else {
            $json['res'] = getPowerTwo($name, $value);
        }
        return json_encode($json, 320);
    }
}
